package cn.mjnxin.iot.connector.worker;

import cn.mjnxin.iot.base.domain.ChannelData;
import cn.mjnxin.iot.base.log.LogWorker;
import cn.mjnxin.iot.base.process.DataProcessWorker;
import cn.mjnxin.iot.connector.cache.HostRuntimeCache;
import cn.mjnxin.iot.connector.context.ConnectorContext;
import io.netty.channel.Channel;

/**
 * 上行报文发送工： 前置报文实际发送终端
 * @author CLG 2023年11月30日
 * @version V1.0.0
 */
public class Connector2GateWorker extends DataProcessWorker<ChannelData> {
	private final boolean            isHost;
	private final String             gateAddress;

    private static Connector2GateWorker             worker       = null;

	//非单例模式：调用一次就初始化一次
	public static void init(int poolSize, String gateAddress, boolean isHost) throws Exception {
		worker = new Connector2GateWorker(poolSize, gateAddress, isHost);
	}

    public static Connector2GateWorker getInstance() {
    	return worker;
    }
    
	public Connector2GateWorker(int poolSize, String gateAddress, boolean isHost) throws Exception {
		super(poolSize, "Connector2GateWorker");
		this.gateAddress = gateAddress;
		this.isHost = isHost;
		this.start();
	}

	@Override
	protected void proccess(ChannelData channelData) throws Exception {
		String gateAddress = channelData.getGateAddress();
		final Channel channel;
		if (gateAddress == null) {
			if (isHost) {
				gateAddress = ConnectorContext.getGateAddressByPeerAddress(channelData.getTerminalAddress());
				channel = HostRuntimeCache.getGateChannel(gateAddress);
			}
			else {
				channel = HostRuntimeCache.getGateChannel(this.gateAddress);
			}
		}
		else {
			channel = HostRuntimeCache.getGateChannel(gateAddress);
		}
		if (channel == null) {
			LogWorker.error(ConnectorContext.CONNECTOR_NAME + "与网关断连，无法发送报文");
			return;
		}
	    channel.writeAndFlush(channelData);
	}
}
